<?php

/**
 * Encode an array
 *
 * @param array &$var
 */
function urlencode_array(&$var)
{
	if (is_array($var)) {
		foreach (array_keys($var) as $k) {
			$var[$k] = urlencode($var[$k]);
		}
	}
}

/**
 * Function to redirect a user to certain pages
 */
function redirect_entete($url) {
	header("Location: " . APPLICATION_URL . $url);
	exit();
	//echo "<meta http-equiv=\"Refresh\" content=\"0; " .APPLICATION_URL.$url ."\">";
}

/**
 * V�rifier si la page courente est le page qu'on veut comparer
 */
function is_page_courante($page) {
	//return ('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] == APPLICATION_URL . '/' . $page);
	$controller = DRX::load("controller");
	return $controller == $page;
}

/*
function get_value($variable, $is_number = true, $default = "") {
	if ($is_number)
		return isset($_GET[$variable]) ? $_GET[$variable] : (isset($_POST[$variable]) ? $_POST[$variable] : intval($default));
	return isset($_GET[$variable]) ? $_GET[$variable] : (isset($_POST[$variable]) ? $_POST[$variable] : $default);
} */

// check login and use SHA1 to encode password
function connecter_utilisateur($login, $pwd, $project = USER_PROJECT_ACCESS_ALLOWED_GALLERY) {

	$acces = new Login();

	$acces->whereAdd("EMAIL = '" . mysql_real_escape_string($login) . "'");
	$acces->whereAdd("PASS = '" . sha1(mysql_real_escape_string($pwd)) . "'");

	switch($project){
		case USER_PROJECT_ACCESS_ALLOWED_VODAFONELIVE:
			$acces->ALLLOWED_VL = 1;
			break;

		case USER_PROJECT_ACCESS_ALLOWED_GALLERY:
			$acces->ALLLOWED_GALLERY = 1;
			break;

		case USER_PROJECT_ACCESS_ALLOWED_FAST:
			$acces->ALLLOWED_FAST = 1;
			break;
	}

	$acces->DISABLED = 0;
	$acces->find();

	if ($acces->fetch())
		return $acces;

	return null;

}

// check login by ID
function connecter_utilisateur_byID($id)
{
	$acces = new Login();

	$acces->whereAdd("ID = " . $id);

	$acces->DISABLED = 0;
	$acces->find();

	if ($acces->fetch())
		return $acces;

	return null;
}

function get_url_request($main_url) {
	$request = array_merge($_POST, $_GET);
	return get_link_from_array($main_url, $request);
}

function get_link_from_array($base_url, $request) {
	$url = $base_url;
	$i = 0;
	if (sizeof($request) == 0)
		$url .= "?";

	foreach($request as $key => $value) {
		if ($i == 0) {
			$url .= "?" . $key . "=" . $value;
			$i++;
			continue;
		}
		$url .= "&" . $key . "=" . $value;
	}
	return $url;
}

function get_action($prefix = "_") {
	$act = isset($_GET["act"]) ? $_GET["act"] : (isset($_POST["act"]) ? $_POST["act"] : "");
	if (isset($_POST[$prefix . "annuler"])) {
		$act = "post_annuler";
	}
	if (isset($_POST[$prefix . "modifier"])) {
		$act = "post_modifier";
	}
	elseif (isset($_POST[$prefix . "supprimer"])) {
		$act = "post_supprimer";
	}
	elseif (isset($_POST[$prefix . "valid_supprimer"])) {
		$act = "post_valid_supprimer";
	}
	elseif (isset($_POST[$prefix . "annuler_creer"])) {
		$act = "post_annuler_creer";
	}
	return $act;
}

function set_link_retour($link, $name_obj) {
	$_SESSION[$name_obj . "_link_retour"] = get_url_request($link);
}

function get_link_retour_4_redirect($name_obj,$default = "") {
	if (isset($_SESSION[$name_obj . "_link_retour"]))
		return str_replace("&amp;", "&", $_SESSION[$name_obj . "_link_retour"]);
	return $default;
}

function date_to_date_sql($date_convert) {

	$pos = strpos($date_convert, '/');
	if ($pos === false)
		return $date_convert;

	list($day, $month, $year) = explode("/", $date_convert);

	if (($year == "1970") && ($month == "01" || $month == "1") && ($day == "01" || $day == "1"))
		return "1970-01-01";

	if (!is_numeric($day) || !is_numeric($month) || !is_numeric($year))
		return "";

	if ($day < 1 || $day > 31)
		return "";
	if ($month < 1 || $month > 12)
		return "";
	if ($year < 0 || $year > 10000)
		return "";

	//if (check_date($date_convert))
	return date("Y-m-d", mktime(0, 0, 0, intval($month), intval($day), intval($year)));

}

function date_sql_to_date($date_convert) {
	//$date_convert = "yyyy-mm-dd";
	$pos = strpos($date_convert, '-');
	if ($pos === false)
		return $date_convert;

	list($year, $month, $day) = explode("-", $date_convert);
	return $day . "/" . $month . "/" . $year;
}

function check_date($date) {
	$date = trim($date);
	if (empty($date)) {
		return false;
	}

	$date_array = explode("/", $date);
	$day = isset($date_array[0]) ? $date_array[0] : - 1;
	$month = isset($date_array[1]) ? $date_array[1] : - 1;
	$year = isset($date_array[2]) ? $date_array[2] : - 1;

	if (!is_numeric($day) || !is_numeric($month) || !is_numeric($year))
		return FALSE;

	if ($day < 1 || $day > 31)
		return false;
	if ($month < 1 || $month > 12)
		return false;
	if ($year < 0 || $year > 10000)
		return false;

	if (checkdate($month, $day, $year)) {
		return true;
	}
	else {
		return false;
	}
}

function check_time($time) {
	if (empty($time))
		return true;

	$time_array = explode(":", $time);
	$heure = isset($time_array[0]) ? $time_array[0] : - 1;
	$minute = isset($time_array[1]) ? $time_array[1] : - 1;

	if ($heure >= 0 && $heure <= 23 && $minute >= 0 && $minute <= 59)
		return true;
	return false;
}

function html_decode_post() {
	foreach($_POST as $key=>$val) {
		if (!is_array($_POST[$key])) {
			$_POST[$key] = utf8_decode(trim($val));
		}
	}
}

function html_decode_all() {
	foreach($_POST as $key=>$val) {
		$_POST[$key] = utf8_decode(trim($val));
	}
	foreach($_GET as $key=>$val) {
		$_GET[$key] = utf8_decode(trim($val));
	}
	foreach($_COOKIE as $key=>$val) {
		$_COOKIE[$key] = utf8_decode(trim($val));
	}
}

function get_random_code($length) {
	$str = '';
	for ($i = 0; $i < $length; $i++) {
		$feed = "0123456789";
		$str .= substr($feed, rand(0, strlen($feed) - 1), 1);
	}
	return $str;
}

function format_sql_prix(&$prix) {
	$prix = str_replace(", ", ".", $prix);
	$prix = str_replace(" ", "", $prix);
	$prix = round($prix, 2);
}

function sommer(&$n, $value) {
	if ($value == '' || $value == NULL) {
		$value = 0;
	}

	if (!isset($n)) {
		$n = $value;
	}
	else {
		$n += $value;
	}
}

function stocker_erreur_sur_lien(&$liste_erreurs, $nom_lien, $nom_format, $erreur) {
	if (! isset($liste_erreurs[$nom_lien])) {
		$liste_erreurs[$nom_lien] = array();
	}

	if (! isset($liste_erreurs[$nom_lien][$nom_format])) {
		$liste_erreurs[$nom_lien][$nom_format] = array();
	}

	$liste_erreurs[$nom_lien][$nom_format][] = $erreur;
}

// Verifier la date de d�but et la date de fin
function check_debut_fin($debut, $fin) {
	return (strtotime(date_to_date_sql($debut)) <= strtotime(date_to_date_sql($fin)));
}

function check_debut($debut) {
	return (strtotime(date_to_date_sql($debut) . " " . date("H:i:s")) >= time());
}

function check_reservation($reservation, $debut) {
	return (strtotime($reservation) >= time() && strtotime($reservation) <= strtotime($debut));
}

// Elever un jour de la date
function elever_date($date) {
	if ($date == '')
		return '';

	$date = strtotime(date_to_date_sql(trim($date)));
	$date += 86400; // ajout 1 jour.
	return date('Y-m-d', $date);
}

// Diminuer un jour de la date
function diminuer_date($date) {
	if ($date == '')
		return '';

	$date = strtotime($date);
	$date -= 86400; // moins 1 jour.
	return date('Y-m-d', $date);
}

function array_to_str_list($data) {
	if (sizeof($data) == 0)
		return "( '' )";
	$i = 0;
	$str = "";
	foreach($data as $key=>$value) {
		if ($i == 0)
			$str .= "( $key";
		else
			$str .= ", $key";
		$i++;
	}
	$str .= " )";
	return $str;
}

function qencode($str) {
	$str = preg_replace("[\r\n]", "", $str);
	$str = preg_replace('/( [\000-\011\013\014\016-\037\075\077\137\177-\377] )/e',
		 "'='.sprintf( '%02X', ord( '\1' ))", $str);
	$str = str_replace(" ", "_", $str);
	return $str;
}

function encode_mime($str) {
	$deb = "=?iso-8859-1?q?";
	$fin = "?=";
	$crlf = "\r\n";

	$longueur = 75 - strlen($deb) - strlen($fin);
	$longueur_step = floor($longueur / 3); // Ratio 1/3 sur encodage q pour etre sur

	$encoded = "";

	for ($i = 0; $i < strlen($str); $i += $longueur_step) {
		$encoded .= ' ' . $deb . qencode(substr($str, $i, $longueur_step)) . $fin . $crlf;
	}

	// On enleve le premier espace et le dernier crlf
	return substr($encoded, 1, - strlen($crlf));
}

/**
 * Check if the email string is valided. That is the email that has:
 * Domain name rule: - Use only letters, numbers, or hyphen ('-')
 * 					 - Can not begin or end with a hyphen
 * 					 - Must have less than 63 characters, not include extension
 *
 * @param string $email
 * @return true if $email is a valid email; false otherwise
 */
function checkEmailValide($email)
{
	$patterns = '/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/ix';
	/*$patterns = '/^(.+)'.
				 '[@]'.
				 '([^-~!@#$%^&*()_+={\\[\\]}:;"\'<,>.?\/\\|\\\\]' .
				 '[-a-z0-9]{0,62}' .
				 '[^-~!@#$%^&*()_+={\\[\\]}:;"\'<,>.?\/\\|\\\\])'.
				 '\.'.
				 '([a-z]{2}'.
				 '|com|net|edu|org'.
				 '|gov|mil|int|biz'.
				 '|pro|info|arpa|aero'.
				 '|coop|name|museum)$/ix';*/

	$FILTER = '"'."\'";
	$email = str_replace(str_split($FILTER), "", $email);

	if(preg_match($patterns,trim($email), $matches)==1)
		return true;
	return false;
}

/**
 * Check whether the url is valid
 *
 * @param unknown_type $url
 * @return unknown
 */
function checkValidUrl($url)
{
	$url = trim($url);
	if (strpos($url,' ') !== false) {
		return false;
	}

	$patterns = '/^(http|https|tel|wtai)?:\/\/[\w|\-]+(\.[^\.]+)+$/i';

	if(preg_match($patterns,trim($url), $matches)==1)
	{
	 	return true;
	}
	return false;
}

function getMoisText($mois)
{
	switch($mois) {
		case 1 :
			return _LB_JANVIER;
		case 2 :
			return _LB_FEVRIER;
		case 3 :
			return _LB_MARS;
		case 4 :
			return _LB_AVRIL;
		case 5 :
			return _LB_MAI;
		case 6 :
			return _LB_JUIN;
		case 7 :
			return _LB_JUILLET;
		case 8 :
			return _LB_AOUT;
		case 9 :
			return _LB_SEPTEMBRE;
		case 10 :
			return _LB_OCTOBRE;
		case 11 :
			return _LB_NOVEMBRE;
		case 12 :
			return _LB_DECEMBRE;
	}
}

function url_exists($url) {
	//d�sactivation du test
	return true;

	$ch = curl_init();
	curl_setopt ($ch, CURLOPT_URL, $url);
	curl_setopt ($ch, CURLOPT_HEADER, 0);
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
	curl_exec ($ch);
	$exists = (curl_errno($ch) == 0);
	curl_close ($ch);
	return $exists;

}

function datediff($interval, $datefrom, $dateto, $using_timestamps = false)
{
 /*
	$interval can be:
	yyyy - Number of full years
	q - Number of full quarters
	m - Number of full months
	y - Difference between day numbers
	 (eg 1st Jan 2004 is "1", the first day. 2nd Feb 2003 is "33". The datediff is "-32".)
	d - Number of full days
	w - Number of full weekdays
	ww - Number of full weeks
	h - Number of full hours
	n - Number of full minutes
	s - Number of full seconds (default)
 */

 if (!$using_timestamps)
 {
	$datefrom = strtotime($datefrom, 0);
	$dateto = strtotime($dateto, 0);
 }
 $difference = $dateto - $datefrom; // Difference in seconds

 switch($interval) {

	case 'yyyy': // Number of full years

	 $years_difference = round($difference / 31536000);
	 if (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom), date("j", $datefrom), date("Y", $datefrom)+$years_difference) > $dateto) {
		$years_difference--;
	 }
	 if (mktime(date("H", $dateto), date("i", $dateto), date("s", $dateto), date("n", $dateto), date("j", $dateto), date("Y", $dateto)-($years_difference+1)) > $datefrom) {
		$years_difference++;
	 }
	 $datediff = $years_difference;
	 break;

	case "q": // Number of full quarters

	 $quarters_difference = round($difference / 8035200);
	 while (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom)+($quarters_difference*3), date("j", $dateto), date("Y", $datefrom)) < $dateto) {
		$months_difference++;
	 }
	 $quarters_difference--;
	 $datediff = $quarters_difference;
	 break;

	case "m": // Number of full months

	 $months_difference = round($difference / 2678400);
	 while (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom)+($months_difference), date("j", $dateto), date("Y", $datefrom)) < $dateto) {
		$months_difference++;
	 }
	 $months_difference--;
	 $datediff = $months_difference;
	 break;

	case 'y': // Difference between day numbers

	 $datediff = date("z", $dateto) - date("z", $datefrom);
	 break;

	case "d": // Number of full days

	 $datediff = round($difference / 86400);
	 break;

	case "w": // Number of full weekdays

	 $days_difference = round($difference / 86400);
	 $weeks_difference = round($days_difference / 7); // Complete weeks
	 $first_day = date("w", $datefrom);
	 $days_remainder = round($days_difference % 7);
	 $odd_days = $first_day + $days_remainder; // Do we have a Saturday or Sunday in the remainder?
	 if ($odd_days > 7) { // Sunday
		$days_remainder--;
	 }
	 if ($odd_days > 6) { // Saturday
		$days_remainder--;
	 }
	 $datediff = ($weeks_difference * 5) + $days_remainder;
	 break;

	case "ww": // Number of full weeks

	 $datediff = round($difference / 604800);
	 break;

	case "h": // Number of full hours

	 $datediff = round($difference / 3600);
	 break;

	case "n": // Number of full minutes

	 $datediff = round($difference / 60);
	 break;

	default: // Number of full seconds (default)

	 $datediff = $difference;
	 break;
 }

 return $datediff;
}

function isBetween($date, $start_date, $end_date)
{

	if(datediff("d", $start_date, $date) >= 0 && datediff("d", $date, $end_date) >= 0)
	{
		return true;
	}
	else
	{
		return false;
	}
}

if(!function_exists('cal_days_in_month')) {
function cal_days_in_month($month, $year)
{
	return $month == 2 ? $year % 4 ? 28 : 29 : ($month % 7 % 2 ? 31 : 30);
}
}

function addDay($date, $day, $format = "Y/m/d") {
	$time = strtotime($date);
	return date($format, mktime(0, 0, 0, date("m", $time), $day + date("d", $time), date("y", $time)));
}

function addHour($date, $hour, $format = "Y-m-d H:i:s") {
	$time = strtotime($date);
	return date($format, $time + $hour * 60 * 60);
}

function addMonth($date, $month, $format = "Y/m/d") {
	$time = strtotime($date);
	return date($format, mktime(0, 0, 0, $month + date("m", $time), date("d", $time), date("y", $time)));
}

function dateFormat($date, $format) {
	return date($format, strtotime($date));
}

/*
url_exists is copied from project RegiePub2 and placed at line 420
function url_exists($url) {
	$file = @fopen($url,"rb");
	if (!$file)
		return false;
	return true;
}
*/
function format_number($number, $number_of_decimals = 0, $decimal_point = '.', $thousands_separate = ',')
{
	if (trim($number)=="")
		return 0;
	else
		return number_format($number, $number_of_decimals, $decimal_point, $thousands_separate);
}

function format_price($price) {
	return format_number($price, 2);
}

function convertToTextSimple($str) {
	$str = str_replace(" ","",$str);
	$txt = preg_replace('/[^a-zA-Z0-9_]/','',$str);
	return $txt;
}

function nextMonday($time) {
	return strtotime("next Monday", $time);
}

function nextSunday($time) {
	return strtotime("next Sunday", $time);
}

function removeIdFiche($filename) {
	$pos1 = strrpos($filename, "_");
	$pos2 = strrpos($filename, ".");
	return substr($filename, 0, $pos1) . substr($filename, $pos2);
}

function generatePassword($length = DEFAULT_PASSWORD_LENGTH)
{

 // start with a blank password
 $password = '';

 // define possible characters
 $possible = '0123456789bcdfghjkmnpqrstvwxyz';

 // set up a counter
 $i = 0;

 // add random characters to $password until $length is reached
 while ($i < $length) {

	// pick a random character from the possible ones
	$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);

	// we don't want this character if it's already in the password
	if (!strstr($password, $char)) {
	 $password .= $char;
	 $i++;
	}

 }

 // done!
 return $password;

}

//<!-- salimane start edit-->
function textvalid($e)
{
	if (trim($e) == "" || $e == null || strlen($e) == 0)
		return false;
	else
		return true;
}

function getVarFromLink($url,$var)
{
	$pattern = "/\?.*".$var."dasdsad=([^&]*)/";
	preg_match($pattern,$url,$matches);

	if (isset($matches[1][0]));
		return $matches[1][0];
	return "";

}

function addParamToURL($url,$param_array)
{
	$url.='?';

	foreach ($param_array as $name => $value)
		if (($name!="") && ($value!=""))
			$url.=$name."=".$value."&";

	return substr($url,0,strlen($url)-1);
}

//<!-- salimane end edit-->

function randomCode($length = 10)
{
 // start with a blank password
 $code = "";

 // define possible characters
 $possible = "0123456789bcdfghjkmnpqrstvwxyz_)(*^%$!";

 // set up a counter
 $i = 0;

 // add random characters to $password until $length is reached
 while ($i < $length) {

	// pick a random character from the possible ones
	$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);

	// we don't want this character if it's already in the password
	if (!strstr($code, $char)) {
	 $code .= $char;
	 $i++;
	}

 }
 // done!
 return $code;

}

function xlsColumn($str)
{
	return ord($str) - 65;
}
